<template>
    <div class='roles'>
        <p class="top_p"><el-button type="text" @click="goHome" class="sy">首页e</el-button>&emsp;/&emsp;权限管理&emsp;/&emsp;角色列表</p>

          <div class="addusers">
            <el-button type="primary" @click="showroles = true">添加角色</el-button>
        </div>
         <el-table
    :data="listData"
    style="width: 100%">
    <el-table-column type="expand">
      <template slot-scope="props">
        <div class="dvbtn">
          <div v-for="(item,i) in  props.row.children" :key="i" class="dvcont"> 
            <div class="conleft">
          <el-tag closable type="" @close="delrole(props,item)">{{item.authName}}</el-tag>
          <i class="el-icon-caret-right"></i>
            </div>
          <div>
            <div v-for="(ite,ind) in item.children" :key="ind" class="dvtest">
          <el-tag closable type="success" @close="delrole(props,ite)">{{ite.authName}}</el-tag>
          <i class="el-icon-caret-right"></i>
          <span v-for="(it,index) in ite.children" :key="index">
          <el-tag closable type="warning" @close="delrole(props,it)">{{it.authName}}</el-tag>
          </span>
          </div>
          </div>
          
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      label="#"
      type="index"
      :index="setindex"
      prop="id">
    </el-table-column>
    <el-table-column
      label="角色名称"
      prop="roleName">
    </el-table-column>
    <el-table-column
      label="角色描述"
      prop="roleDesc">
    </el-table-column>
    <el-table-column
      label="操作"
      prop="">
      <template slot-scope="scope">
               <el-button type="primary" class="el-icon-edit" size="mini" @click="upsetusers(scope)">编辑</el-button>
        <el-button type="danger" class="el-icon-delete" size="mini" @click="delurole(scope)">删除</el-button>
      <el-button type="warning" class="el-icon-setting" size="mini"  @click="jobaddshow(scope)">分配角色</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 添加的弹框 -->
  <div class="allContext" v-show="showroles">
      <div class="contexts">
        <div class="textTop">
        <p class="addtexttop">添加用户</p>
         <span @click="showroles = false">X</span>
        </div>

       <el-form
            :model="addrole"
            :rules="rules"
            ref="formLabelAlign"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item
              label="角色名称"
              prop="name"
            >
              <el-input v-model="addrole.name"></el-input>
            </el-form-item>
            <el-form-item
              label="角色描述"
            >
              <el-input v-model="addrole.userdes"></el-input>
            </el-form-item>
           
            <!-- 按钮 -->
            <el-form-item class="btn">
              <el-button @click="showroles = false">取消</el-button>
              <el-button
                type="primary"
                @click="addusers"
              >确定</el-button>
            </el-form-item>
          </el-form>


      </div>
  </div>
  <!-- 分配权限  -->
  <div class="allContext" v-show="jobshow">
      <div class="contexts">
        <div class="textTop">
        <p class="addtexttop">分配权限</p>
         <span @click="setshowdes">X</span>
        </div>
<el-tree
  :data="joblist"
  show-checkbox
  default-expand-all
  node-key="id"
  ref="tree"
  highlight-current
    :default-checked-keys="checkjob"
  :props="defaultProps">
</el-tree>
<el-button
                type="primary"
                @click="getkeys"
              >确定</el-button> 
      </div>
  </div>
   <!-- 添加的弹框 -->
  <div class="allContext" v-show="upshowrole">
      <div class="contexts">
        <div class="textTop">
        <p class="uptexttop">添加用户</p>
         <span @click="upshowrole = false">X</span>
        </div>

       <el-form
            :model="uprole"
            :rules="rules"
            ref="formLabelAlign"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item
              label="角色名称"
              prop="name"
            >
              <el-input v-model="uprole.roleName"></el-input>
            </el-form-item>
            <el-form-item
              label="角色描述"
            >
              <el-input v-model="uprole.roleDesc"></el-input>
            </el-form-item>
           
            <!-- 按钮 -->
            <el-form-item class="btn">
              <el-button @click="showroles = false">取消</el-button>
              <el-button
                type="primary"
                @click="upusers"
              >确定</el-button>
            </el-form-item>
          </el-form>
      </div>
    </div>
 </div>
</template>

<script>
import {
  getmenus,
  getroles,
  addroles,
  upuserRoles,
  delrole,
  delroledes,
  getdesAll,
  setdesall
} from "../api/getData.js";
import { setTimeout } from "timers";
export default {
  data() {
    return {
      listData: [],
      addrole: {
        name: "",
        userdes: ""
      },
      rules: {
        name: [{ required: true, message: "请输入角色名", trigger: "blur" }]
      },
      uprole: {
        id: null,
        roleDesc: "",
        roleDesc: ""
      },
      rules: {
        name: [{ required: true, message: "请输入角色名", trigger: "blur" }]
      },
      showroles: false,
      upshowrole: false,
      jobshow: false,
      joblist: [],
      defaultProps: {
        children: "children",
        label: "authName"
      },
      checkjob: [],
      userdesId: null
    };
  },
  mounted() {
    this.getlist();
  },
  methods: {
    goHome() {
      this.$router.push("/greet");
    },
    getlist() {
      getroles().then(res => {
        console.log(res);
        this.listData = res.data;
      });
    },
    setindex(index) {
      return index + 1;
    },
    addusers() {
      addroles({
        roleName: this.addrole.name,
        roleDesc: this.addrole.userdes
      }).then(res => {
        console.log(res);
        if (res.meta.status == 201) {
          this.showroles = false;
          this.addrole.name = "";
          this.addrole.userdes = "";
          this.$message({
            message: "数据添加成功",
            type: "success"
          });
          this.getlist();
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },
    upsetusers(item) {
      this.uprole.id = item.row.id;
      this.uprole.roleName = item.row.roleName;
      this.uprole.roleDesc = item.row.roleDesc;
      this.upshowrole = true;
    },
    upusers() {
      upuserRoles(this.uprole).then(res => {
        if (res.meta.status == 200) {
          this.upshowrole = false;
          this.uprole.roleName = "";
          this.uprole.roleDesc = "";
          this.getlist();
        }
      });
    },
    delurole(e) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delrole(e.row.id).then(res => {
            if (res.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            } else {
              this.$message({
                type: "info",
                message: "服务器被外星人抢走了"
              });
            }
            this.getlist();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    delrole(item, id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delroledes({ id: item.row.id, rid: id.id }).then(res => {
            if (res.meta.status == 200) {
              this.$message({
                message: "权限修改成功",
                type: "success"
              });
              this.getlist();
            } else {
              this.$message.error(res.meta.msg);
            }
            this.getlist();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //点击分配按钮时候
     jobaddshow(item) {
       //获取所有权限的数据
      getdesAll().then(res => {
        //保存起来
        this.joblist = res.data;
      });
      this.checkjob = [];
      //让弹框显示
      this.jobshow = true;
      //保存当前条的id
      this.userdesId = item.row.id;
      //获取最里面数据的id
      //可以使用一个递归函数
      function allid(val) {
        let arr = null;
        //判断是数组的时候进行循环
        if (Array.isArray(val)) {
          arr = [];
          val.forEach(it => {
            //如果有子数据就继续调用函数，递归函数必须有退出条件，如果没有children （秋准）就退出递归
            if (it.children != undefined) {
              //递归调用
              arr.push(...allid(it.children));
            } else {
              //如果有的直接添加到数组里
              arr.push(it.id);
            }
          });
        } else {
          // 不是数组的话就直接保存
          arr = val.id;
        }
        //把获取到的子id返回
        return arr;
      }
      console.log(allid(item.row.children));
        //把获取好的数据保存起来
      this.checkjob =  allid(item.row.children);
    },
    //确定分配的时候把修改后的所有别选中权限的id进行上传，包括父级id
    getkeys() {

      // getCheckedKeys	若节点可被选择（即 show-checkbox 为 true），
      //则返回目前被选中的节点的 node-key 所组成的数组	(leafOnly) 接收一个 boolean 类型的参数，
      //若为 true 则仅返回被选中的叶子节点的 keys，默认值为 false
      let id = this.$refs.tree.getCheckedKeys();
      //join数组转换字符串传值是分隔符
      setdesall({ id: this.userdesId, rids: id.join(",") }).then(res => {
        // console.log(res);
        if (res.meta.status == 200) {
          this.jobshow = false;
          this.userdesId = "";
          this.checkjob = [];
          this.$message({
            message: "数据更新成功",
            type: "success"
          });
          this.getlist();
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },
    setshowdes() {
      this.checkjob = [];
      this.jobshow = false;
      this.userdesId = null;
    }
  },
  components: {}
};
</script>

<style lang='scss'>
.roles {
  background: #fff;
  margin: 10px;
  overflow: hidden;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.addusers {
  margin: 10px 0;
  padding: 0 10px;
}
.addusers .el-button {
  height: 40px;
}
.allContext {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 999;
  overflow: scroll;
}
.contexts {
  width: 550px;
  background: #fff;
  margin: 100px auto;
  padding: 15px 15px 50px 15px;
}
.addtexttop {
  font-size: 19px;
  flex: 1;
}
.textTop {
  display: flex;
  margin-bottom: 20px;
}
.cinp {
  width: 100%;
}
.cinp p {
  width: 100%;
  height: 40px;
  display: flex;
  margin: 10px 0;
  line-height: 40px;
}
.cinp p span {
  width: 15%;
  text-align: right;
}
.cinp p input {
  width: 100%;
  margin: 0 10px;
  border-radius: 3px;
  padding-left: 10px;
  border: 1px solid #aaa;
}
.dvcont {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ccc;
}
.dvtest {
  padding: 15px;
  border-bottom: 1px solid #ccc;
}
.dvtest span {
  margin: 0 5px;
}
.dvcont div {
  height: 100%;
}
.conleft {
  padding-right: 50px;
}

</style>
